﻿# -------------------------------------------------- #
# Windows Service Principal Name (SPN) Configuration #
# -------------------------------------------------- #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' executing SPN '$($script.type)' configuration ... " -NoNewLine $true
$session = Get-VirtualMachineInstancePowerShellSession -Subscription $subscription -VirtualMachineName $virtualMachineName
switch ($script.type)
{
	"Add"
	{
        # Add account SPN
	    Invoke-Command -Session $session -ScriptBlock {
		    param([string]$name, [string]$account)
		    setspn -S $name $account | Out-Null
	    } -ArgumentList $script.spn, $script.account
	}
	"Remove"
	{
        # Remove account SPN
	    Invoke-Command -Session $session -ScriptBlock {
		    param([string]$name, [string]$account)
		    setspn -D $name $account | Out-Null
	    } -ArgumentList $script.spn, $script.account
	}
	"Set Delegation"
	{
        # Set whether an account is trusted for Kerberos delegation
	    Invoke-Command -Session $session -ScriptBlock {
		    param([string]$identity, [string]$enable)
            Import-Module ActiveDirectory
		    Set-ADAccountControl -Identity $identity -TrustedForDelegation $([bool]::Parse($enable))
	    } -ArgumentList $script.identity, $script.enable
	}
	default
	{
		throw "SPN type '$($script.type)' is not supported."
	}
}
Remove-PSSession $session
Write-Text "done."